package com.xinggq.pay.service.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Arrays;
import java.util.List;

/**
 * AppId校验配置类
 * 默认所有请求都需要校验appId，只需配置不需要校验的路径
 *
 * @author xinggq
 * @since 2025/1/10
 */
@Data
@Component
@ConfigurationProperties(prefix = "app.id.validation")
public class AppIdValidationConfig {

  /**
   * 获取context-path
   */
  @Value("${server.servlet.context-path}")
  private String contextPath;

  /**
   * 路径匹配器
   */
  private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


  /**
   * 不需要校验appId的路径模式列表
   * 支持Ant路径匹配模式
   */
  private List<String> excludedPatterns = Arrays.asList(
      "/public/**",
      "/webjars/**",
      "/yse/callback/**",
      "/health",
      "/actuator/**",
      "/swagger-ui/**",
      "/v3/api-docs/**",
      "/favicon.ico",
      "/doc.html",
      "/error"
  );

  /**
   * 判断指定路径是否需要校验appId
   * 默认所有请求都需要校验，只有在排除列表中的路径才不需要校验
   *
   * @param requestPath 请求路径
   * @return true-需要校验，false-不需要校验
   */
  public boolean isAppIdRequired(String requestPath) {
    requestPath = requestPath.startsWith("/") ? requestPath : "/" + requestPath;
    String contextPath = this.contextPath.startsWith("/") ? this.contextPath : "/" + this.contextPath;
    requestPath = requestPath.startsWith(contextPath) ? requestPath.substring(contextPath.length()) : requestPath;
    // 检查排除列表，如果匹配则不需要校验
    for (String excludedPattern : excludedPatterns) {
      if (PATH_MATCHER.match(excludedPattern, requestPath)) {
        return false;
      }
    }
    // 默认需要校验
    return true;
  }

}